package com.widevision.ListActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import net.widevision.android.R;
import net.widevision.android.TestPost;
import net.widevision.android.TwitterApp;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TimeSpanUtil;
import twitter4j.Twitter;
import twitter4j.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.widevision.adapter.InfoAdapter;
import com.widevision.adapter.InfoBean;
import com.widevision.adapter.TweetAdapter;
import com.widevision.adapter.TweetBean;

@SuppressWarnings("deprecation")
public class UserProfile extends Activity
{
	
	//***********************************//
	private AQuery aq;
	//***********************************//
	
    TwitterApp mTwitter;
    
    Twitter twitter;
	
	User user;
	int h=0;
	ResponseList<Status> TweetList,TweetNameList;
	
	
	TimeSpanUtil timeSpanUtil;

	TweetAdapter tweetAdapter;
	
	TweetBean tweetBean;
	
	InfoAdapter infoAdapter;
	
	InfoBean infoBean;
	
	private static final String twitter_consumer_key = "JXmXcE5yFPLIRCCtQ79eg";
	private static final String twitter_secret_key = "dnVojAwaewvEt8E2QwLYtavwm8cdUHwph7lZCaQPMY";
	
	TextView name,followerscount,locationtxt,followingscount,ScreenName,Scroll,TweetText,frnd,follower;

	String username,followers,following,location,StrScreeName,description,infoname;

	String tweetText,Tweet;
	
	String key;
	
	String userscreenname;
	
	ImageView imageView,post,wall,info,message,img;
	
	LinearLayout frndlayout,followerlayout,optionlayout,tweetlayout;
	
	ListView tweetList,infolist;
		
	Status Text;
	
	InputStream is;
	
	ResponseList<twitter4j.User> frndlisttext;
	
	int followercount,frndcount,id,userId;
	
	int count=0;
		
	boolean isfrnd;
	
	Drawable draobj,twetimgobj;
	
	ArrayList<Object> tweetArrayList,infoArrayList;
	
	ArrayList<Drawable> profileimg,minitwimg,timeimg,frndimg;
	
	ArrayList<String> tweetlist,infoList;
	
	PopupWindow popupWindow ;
	
	static int flag=0;
		
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		//***********************************//
		aq = new AQuery(this);
		//***********************************//
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.profilelist);
		
		name            =(TextView) findViewById(R.id.name);
		followerscount  =(TextView) findViewById(R.id.followers);
		followingscount =(TextView) findViewById(R.id.following);
		frnd			=(TextView) findViewById(R.id.frnd);
		follower		=(TextView) findViewById(R.id.follower);
		Scroll          =(TextView) findViewById(R.id.scroller);
		ScreenName      =(TextView) findViewById(R.id.screenname);
		TweetText       =(TextView) findViewById(R.id.tweettext);
		
		imageView       =(ImageView) findViewById(R.id.proimg);
		post            =(ImageView) findViewById(R.id.post);
		wall			=(ImageView) findViewById(R.id.wall);
		info			=(ImageView) findViewById(R.id.info);
		message			=(ImageView) findViewById(R.id.message);
		img			  	=(ImageView) findViewById(R.id.img);
		
		tweetList       =(ListView) findViewById(R.id.lview);
		infolist        =(ListView) findViewById(R.id.lview1);
	    
	    frndlayout		=(LinearLayout) findViewById(R.id.frndlayout);
		followerlayout	=(LinearLayout) findViewById(R.id.followerlayout);
		
		mTwitter 	= new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

		Scroll.setSelected(true);
		
		Bundle bundle=getIntent().getExtras();
		
		userId=bundle.getInt("USERID");
		
		Log.d("userId>>>", ""+userId);
		
		infoMethod();
	    
	    img.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v)
			{
				if(isfrnd==true)
				{
					user=mTwitter.destroyFriendship(StrScreeName);
					Log.d("destroyFriendship>>>>>>>",StrScreeName);
					img.setBackgroundResource(R.drawable.twfollow);
					infoMethod();
					Toast.makeText(getApplicationContext(), "Unfollowed"+" "+"@"+StrScreeName, Toast.LENGTH_LONG).show();
				}
				else if(isfrnd==false)
				{
					user=mTwitter.createFriendship(StrScreeName);
					Log.d("createFriendship>>>>>>>",StrScreeName);
					img.setBackgroundResource(R.drawable.twunfollow);
					infoMethod();
					Toast.makeText(getApplicationContext(), "Now Following"+" "+"@"+StrScreeName, Toast.LENGTH_LONG).show();
				}
			}
		});
	   
	    post.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent(UserProfile.this,TestPost.class);
				intent.putExtra("SCREENNAME", StrScreeName);
				startActivity(intent);
			}
		    });
		 
		 info.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
				tweetList.setVisibility(View.GONE);
				infolist.setVisibility(View.VISIBLE);
			    info.setBackgroundResource(R.drawable.infotabon);
			    wall.setBackgroundResource(R.drawable.walltaboff);
			    prepararraylistforInfo();
	  		    infoAdapter  = new InfoAdapter(UserProfile.this, infoArrayList);
				infolist.setAdapter(infoAdapter);
		
				}
			});
		 
		 wall.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
				infolist.setVisibility(View.GONE);
			    tweetList.setVisibility(View.VISIBLE);
			    wall.setBackgroundResource(R.drawable.walltabon);
			    info.setBackgroundResource(R.drawable.infotaboff);
			    wallList();
			}
			});
		 Scroll.setText("@"+StrScreeName+"'s Profile"+"                                                                  ");
		 
		 frndlayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent=new Intent(UserProfile.this,FrndName.class);
					intent.putExtra("USERID", userId);
					startActivity(intent);
					
				}
			});
			followerlayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent=new Intent(UserProfile.this,FollowerName.class);
					intent.putExtra("USERID", userId);
					startActivity(intent);
					
				}
			});
			getUserTimeLine();
			wallList();
}
	public void showFavoiratePopup(View view)
    {
		try 
		{

				LayoutInflater popupInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View popupView= popupInflater.inflate(R.layout.popup,(ViewGroup) view.findViewById(R.id.tweetoption));
				PopupWindow popupWindow  = new PopupWindow(popupView , LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, false);
				popupWindow.setOutsideTouchable(true);
				popupWindow.showAsDropDown(view);
		}
		catch (Throwable e)
		{
			e.printStackTrace();
		}

    }
protected void wallList() 
{
	tweetAdapter=new TweetAdapter(UserProfile.this, tweetArrayList,aq);
	tweetList.setAdapter(tweetAdapter);
	wall.setBackgroundResource(R.drawable.walltabon);
	}

private void getUserTimeLine()
{
    tweetArrayList=new ArrayList<Object>();
	 mTwitter 	= new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
	 if (mTwitter.hasAccessToken())
	 {
		 
		 TweetList=mTwitter.getUserTimeLine();
		 
		 Log.d("usertweetList>>>>>>>", ""+TweetList);
		
   	     for(int j=0;j<=3;j++)
			{
				Text=TweetList.get(j);
				Tweet=Text.getText();
				username=Text.getUser().getName();
				String ScreeName=Text.getUser().getScreenName();
				Date date=Text.getCreatedAt();
				URL u=Text.getUser().getProfileImageURL();
				String tweetuserimg=String.valueOf(u);
//				try {
//					is = u.openStream();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				twetimgobj = Drawable.createFromStream(is, "src name");
				
			    String time=timeSpanUtil.toTimeSpanString(date);

				String screenName=" "+("@")+ScreeName;
				
				AddObjectToList(Tweet,username,screenName,time,tweetuserimg);
			}
	 }
}

private void AddObjectToList(String tweet,String username,String screenName,String time,String tweetimg) 
{
				tweetBean = new TweetBean();
				tweetBean.setTweet(tweet);
				tweetBean.setUserName(username);
				tweetBean.setScreenName(screenName);
				tweetBean.setTime(time);
				tweetBean.setProfileimg(tweetimg);
				tweetArrayList.add(tweetBean);
}

private void infoMethod() 
{

	    if (mTwitter.hasAccessToken())
	    {
			 
			 user=mTwitter.showUser(userId);
			
			 StrScreeName=user.getScreenName();
		     
		     ScreenName.setText(StrScreeName);
			 
			 username=user.getName();
			 
			 name.setText(username);
			 
  		     URL u=user.getProfileImageURL();
			 
  		     try 
  		     {
					is = u.openStream();
  		     }
  		     catch (IOException e) 
  		     {
					e.printStackTrace();
  		     }
				
			 draobj = Drawable.createFromStream(is, "src name");
			 
			 imageView.setImageDrawable(draobj);
			    
			 followercount=user.getFollowersCount();
			 Log.d("followercount>>>", ""+followercount);
			 followerscount.setText("("+followercount+")");
			 followerscount.setTextSize(10);
			 
			 frndcount=user.getFriendsCount();
			 followingscount.setText("("+frndcount+")");
			 Log.d("frndcount>>>", ""+frndcount);
			 followingscount.setTextSize(10);
		 }
	    
	     if (mTwitter.hasAccessToken())
	     {
			try
			{
				userscreenname=mTwitter.getScreenName();
				isfrnd=mTwitter.existsFriendship(userscreenname, StrScreeName);
			} 
			catch (IllegalStateException e)
			{
				e.printStackTrace();
			} 
		}
	    if(isfrnd==true)
	    {
			img.setBackgroundResource(R.drawable.twunfollow);
		}
		else if(isfrnd==false){
			
			if(userscreenname.equals(StrScreeName))
			{
				Log.d("no image >>>", "");
			}
			else
			{
				img.setBackgroundResource(R.drawable.twfollow);
			}
			    
		}
		
	}
	protected void prepararraylistforInfo()
	{
		mTwitter 	= new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
		if (mTwitter.hasAccessToken())
		{
		    infoArrayList=new ArrayList<Object>();
		    
	        location=user.getLocation();
	        
			infoname=user.getName();
			
			description=user.getDescription();
	    	
	    	if(infoname != null){
	    		AddObjectToList1(infoname,"Name");
	    	}
	    	if(location != null){
	    		AddObjectToList1(location,"Location");
	    	}
	    	if(description != null){
	    		AddObjectToList1(description,"Description");
	    	}
	}
}
	 private void AddObjectToList1(String value,String type) 
	 {
			infoBean = new InfoBean();
			infoBean.setValue(value);
			infoBean.setType(type);
		    infoArrayList.add(infoBean);
	 }
}
